<?php
/**
* alltosun.com  提交订单
* ============================================================================
* 版权所有 (C) 2009-2015 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 张元昊 (zhangyh@alltosun.com) $
* $Date: 2015-12-28 10:48:04 $
* $Id$
*/

class Action
{

    // 声明是否允许
    private $is_allow_action = false;

    /**
     * 构造验证
     * @return string
     */
    public function __construct()
    {
        // 验证是否有权限提交订单 (只有助理和超级管理员允许提交订单)
        $allow_role = array(user_config::ADMIN, user_config::ASSISTANT);

        if (user_helper::is_allow_action($allow_role)) {
            $this->is_allow_action = true;
        }

    }

    /**
     * 提交订单
     */
    public function trade_order()
    {

        if (!$this->is_allow_action) {
            return array('没有此操作权限', 'error', AnUrl('order/admin'));
        }

        $search_filter = Request::Get('search_filter', array());
        $is_excel = Request::Get('is_excel', 0);

        foreach ($search_filter as $key => $value) {
            $search_filter[$key] = AnFilter::filter_string($value);
        }

        $goods_list = array();

        if(isset($search_filter['user_name']) && $search_filter['user_name'] != '') {

            $user_info = _uri('user', array('user_name' => $search_filter['user_name']));
            $role_type = user_helper::get_user_role_id($user_info['id']);

            if($role_type != '5') {
                return array('此客户角色不是经销商', 'error', AnUrl('order/admin/trade/trade_order'));
            }

            if($user_info) {
                // 判断当前登陆用户是否是助理且选择的经销商是不是自己绑定的经销商
                $cur_role_id = user_helper::get_admin_role_id();
                if (user_config::ASSISTANT == $cur_role_id) {
                    $dealer_ids = user_helper::get_assistant_dealer_ids();
                    if ($dealer_ids) {
                        if (!in_array($user_info['id'], $dealer_ids)) {
                            return array('没有此操作权限', 'error', AnUrl('order/admin'));
                        }
                    } else {
                        return array('没有此操作权限', 'error', AnUrl('order/admin'));
                    }
                }

                $store_info = _uri('store', array('user_id' => $user_info['id']));
                $user_store_info = _uri('user_store', array('user_id' => $user_info['id']));
                if($store_info) {
                    Response::assign('user_info', $user_info);
                    Response::assign('store_info', $store_info);
                }
                $filter = array(
                    'status'  => 1,
                    'is_sale' => 1
                );

                $goods_list = _model('goods')->getList($filter, ' ORDER BY `view_order` DESC, `id` DESC ');
                foreach ($goods_list as $key=>$value) {

                    // 获取商品价格
                    $value['price'] = goods_helper::get_price_by_id($value['id']);
                    // 获取商品库存
                    $value['stock'] = goods_helper::get_stock_by_id($value['id']);

                    $sku_list = goods_helper::get_sku_list($value['id'], $user_store_info['addon_price']);

                    if ($sku_list) {
                        foreach($sku_list as $k => $v) {
                            // 经销商价格等级
                            $dealers_diff_price = dealers_helper::get_dealers_goods_diff_price($user_info['id'], $v['id']);
                            $sku_list[$k]['diff2_price'] = $dealers_diff_price;
                            $sku_list[$k]['price'] = (string)($value['price'] + $dealers_diff_price);
                        }
                        $goods_list[$key]['sku_list'] = $sku_list;
                    }
                }
            }
        }
        //EXCEL导出
        // if ($is_excel) {
        //     $this->export_excel($goods_list);
        // }

        Response::assign('search_filter', $search_filter);
        Response::assign('goods_list', $goods_list);
        Response::display('admin/trade_order.html');
    }

    public function trade_cup_type()
    {
        if (!$this->is_allow_action) {
            return array('没有此操作权限', 'error', AnUrl('order/admin'));
        }

        $goods_list = Request::Post('goods_list', array());

        $store_id = Request::Post('store_id', 0);

        $deliver_type = Request::Post('deliver_type', 0);

        $pay_type = Request::Post('pay_type', 0);

        $note     = Request::Post('note', '');
        if(!$store_id) {
            return array('店铺信息有误[-1]', 'error', AnUrl('order/admin/trade/trade_order'));
        }
        $store_info = _uri('store', $store_id);
        if(!$store_info) {
            return array('店铺信息有误[-2]', 'error', AnUrl('order/admin/trade/trade_order'));
        }
        if(!$goods_list) {
            return array('商品信息有误[-1]', 'error', AnUrl('order/admin/trade/trade_order'));
        }

        $new_goods_list = array();

        foreach ($goods_list as $key => $value) {
            foreach ($value as $k => $v) {
                $new_goods_list[$k][$key] = $v;
            }
        }
        foreach ($new_goods_list as $key => $value) {
            if(!$value['goods_num']) {
                unset($new_goods_list[$key]);
            }
        }

        $order_goods_num = 0;
        //散装商品数量
        $order_bulk_goods_num = 0;
        foreach ($new_goods_list as $k => $v) {
            $goods_info = _uri('goods', $v['goods_id']);
            if(!$goods_info || !$goods_info['status']) {
                return array('包含商品不存在', 'error', AnUrl('order/admin/trade/trade_order'));
            }
            if(!$goods_info['is_sale']) {
                return array('包含商品还未上架', 'error', AnUrl('order/admin/trade/trade_order'));
            }

            //判断是否有散装商品，计算杯的数量
            if($goods_info['category_id'] == 1) {
                $order_bulk_goods_num = $order_bulk_goods_num + $v['goods_num'];
            }
            //计算商品总数
            $order_goods_num = $order_goods_num + $v['goods_num'];
        }

        //记录session
        $_SESSION['trade_param']['goods_list'] = $new_goods_list;
        $_SESSION['trade_param']['store_info'] = $store_info;
        $_SESSION['trade_param']['deliver_type'] = $deliver_type;
        $_SESSION['trade_param']['pay_type'] = $pay_type;
        $_SESSION['trade_param']['note'] = $note;

        if(!$order_bulk_goods_num) {
            // @wangdk 没有被子也要跳转杯子页面
//             Response::redirect(AnUrl('order/admin/trade/save_cup_data'));
//             Response::flush();
//             exit();
        }

        //查询订单数目
        $order_num = order_helper::get_store_order_num($store_id);
        if($order_num > 3) {
            $is_double = 0;
        } else {
            $is_double = 1;
        }

        $cup_data = array();
        if ($order_bulk_goods_num) {
            $return_scale_data = cup_helper::get_order_default_cup_num($order_bulk_goods_num);
            $cup_data = cup_helper::get_dealer_cup_num($store_id, $order_bulk_goods_num, $return_scale_data, $is_double);
        }


        $cup_list = cup_config::$cup_type;
        $box2cup_num = cup_config::$box2cup_num;
        // 获取经销商的仓库地址
        $dealers_address_list = dealers_helper::get_dealer_address_list($store_info['user_id']);

        Response::assign('dealers_address_list', $dealers_address_list);
        Response::assign('order_bulk_goods_num', $order_bulk_goods_num);

        Response::assign('cup_data', $cup_data);
        Response::assign('box2cup_num', $box2cup_num);

        Response::assign('cup_list', $cup_list);
        Response::assign('store_info', $store_info);

        Response::assign('goods_list', $goods_list);
        Response::display('admin/trade_cup_type.html');
    }

    public function ajax_get_cup_data()
    {
        if (!$this->is_allow_action) {
            return array('info' => 'error', 'msg' => '没有此操作权限');
        }
        $cup_list = Request::Post('cup_list', array());
        $store_id = Request::Post('store_id', 0);
        if(!$cup_list) {
            return array('info' => 'error', 'msg' => '杯型类型数据有误');
        }
        if(!$store_id) {
            return array('info' => 'error', 'msg' => '商铺ID有误');
        }
        $cup_box_num = 0;
        foreach ($cup_list as $key => $value) {
            $cup_box_num += $value;
        }
        //查询订单数目
        $order_num = order_helper::get_store_order_num($store_id);
        if($order_num > 3) {
            $is_double = 0;
        } else {
            $is_double = 1;
        }
        $cup_data = cup_helper::get_dealer_cup_num($store_id, $cup_box_num, $cup_list, $is_double);
        return array('info' => 'ok', 'data' => $cup_data);
    }

    public function save_cup_data()
    {
        if (!$this->is_allow_action) {
            return array('没有此操作权限', 'error', AnUrl('order/admin'));
        }

        $user_id = user_helper::get_user_id();

        $order_goods_list = $_SESSION['trade_param']['goods_list'];
        $store_id         = $_SESSION['trade_param']['store_info']['id'];
        $pay_type         = $_SESSION['trade_param']['pay_type'];
        $deliver_type     = $_SESSION['trade_param']['deliver_type'];
        $note             = $_SESSION['trade_param']['note'];
        $store_info       = $_SESSION['trade_param']['store_info'];


        $cup_list   = an_request('cup_list', array(), 'request', 1);
        $addres_id  = an_request('dealer_address_id', 0);

        // 任务备注
        $task_desc = an_request('task_desc','');
        if(!$task_desc) {
            return array('请填写任务备注!', 'error', AnUrl('order/admin/trade/trade_order'));
        }

        if(!$order_goods_list) {
            return array('请传递商品具体信息参数', 'error', AnUrl('order/admin/trade/trade_order'));
        }

        if(!$store_info || $store_info['status'] == 0) {
            return array('经销商不存在或者已删除', 'error', AnUrl('order/admin/trade/trade_order'));
        }

        $user_store_info = _uri('user_store', array('user_id' => $store_info['owner_id']));
        //查询经销商信息
        // $agency_store_info = _uri('store', array('user_id' => $store_info['agency_id']));

        $order_price_sum = 0.00;
        $order_goods_num = 0;

        // 散装商品数量
        $order_bulk_goods_num = 0;

        // 二级经销商差价，注意下面保存用到了这个变量

        $diff_price      = 0;
        $diff_sum_price  = 0;

        foreach ($order_goods_list as $k => $v) {
            $goods_info = _uri('goods', $v['goods_id']);
            if(!$goods_info || !$goods_info['status']) {
                return array('包含商品不存在', 'error', AnUrl('order/admin/trade/trade_order'));
            }
            if(!$goods_info['is_sale']) {
                return array('包含商品还未上架', 'error', AnUrl('order/admin/trade/trade_order'));
            }

            $filter = array(
                    'id' => $v['sku_id'],
                    'goods_id' => $v['goods_id']
                );
            $store_goods_sku_info = _uri('sku', $filter);
            // 算出单件商品的总价格
            if($store_goods_sku_info) {

                if(!$store_goods_sku_info['status']) {
                    return array('包含商品不存在或者已经下架', 'error', AnUrl('order/admin/trade/trade_order'));
                }

                // 算出单件商品的总价格
                $diff_price = dealers_helper::get_dealers_goods_diff_price($store_info['user_id'], $store_goods_sku_info['id']);
                $diff_sum_price = $diff_sum_price + ($diff_price * $v['goods_num']);
                $sku_price = ($store_goods_sku_info['price'] + $user_store_info['addon_price']) + $diff_price;
                $tmp_price = $sku_price * $v['goods_num'];

            } else {
                return array('包含商品信息有误', 'error', AnUrl('order/admin/trade/trade_order'));
            }


            $order_price_sum = $order_price_sum + $tmp_price;

            // 二级经销商的价格
            $sku_goods_price = $store_goods_sku_info['price'] + $diff_price;
            //先构建order_relation_info数据结构
            $tmp_str = 'order_relation_info_'.$k;
            $$tmp_str = array(
                'user_id'     => $store_info['user_id'],
                'goods_id'    => $v['goods_id'],
                'sku_id'      => $v['sku_id'],
                'goods_num'   => $v['goods_num'],
                'addon_price' => $user_store_info['addon_price'],
                'goods_price' => $sku_goods_price,
                // 单品的价格
                'real_price'  => ($sku_goods_price + $user_store_info['addon_price']) * $v['goods_num'],
                // 二级经销商差价
               'diff_sum_price' => ($diff_price + $user_store_info['addon_price'])  * $v['goods_num']
            );

            //判断是否有散装商品，计算杯的数量
            if($goods_info['category_id'] == 1) {
                $order_bulk_goods_num = $order_bulk_goods_num + $v['goods_num'];
            }
            //计算商品总数
            $order_goods_num = $order_goods_num + $v['goods_num'];
        }

        //格式化价钱 保留两位小数
        $order_price_sum = num_keep_two_round($order_price_sum);

        $pay_type_list = order_config::$pay_type;
        if(!$pay_type || !$pay_type_list[$pay_type]) {
            return array('支付方式无效', 'error', AnUrl('order/admin/trade/trade_order'));
        }

        $deliver_type_list = order_config::$deliver_type;

        if(!$deliver_type || !$deliver_type_list[$deliver_type]) {
            return array('配送方式无效', 'error', AnUrl('order/admin/trade/trade_order'));
        }

        // 处理散装商品杯型
        if($order_bulk_goods_num) {
            if(!$cup_list) {
                return array('请传递散装商品具体信息参数', 'error', AnUrl('order/admin/trade/trade_order'));
            }
            $tmp_box_sum = 0;
            $cup_config_list = cup_config::$cup_type;
            //组装信息格式
            $box_type_box = array();
            $cup_list = cup_helper::filter_cup_empty_arr($cup_list);
            foreach($cup_list as $k => $v) {
                //计算此杯型数目
                $tmp_box_sum = $tmp_box_sum + $v;
            }

            // 判断散装商品数量和总箱子数量是否吻合
            if($tmp_box_sum != $order_bulk_goods_num) {
                return array('散装商品数量信息错误', 'error', AnUrl('order/admin/trade/trade_order'));
            }
            //查询订单数目
            $order_num = order_helper::get_store_order_num($store_id);
            if($order_num > 3) {
                $is_double = 0;
            } else {
                $is_double = 1;
            }
            $cup_num_data = cup_helper::get_dealer_cup_num($store_id, $order_bulk_goods_num, $cup_list, $is_double);
        }

        $info = array(
                'type' => 1,
                'price' => $order_price_sum,
                'user_id' => $store_info['user_id'],
                'store_id' => $store_id,
                // 'mobile'  => $mobile,
                'deliver_type' => $deliver_type,
                'pay_type' => $pay_type,
                'goods_num' => $order_goods_num,
                'task_desc' => $task_desc,
                'task_user_id' => $user_id
        );

        // 补充选择仓库地址
       $info = dealers_helper::get_dealer_address_info($store_info['user_id'], $addres_id, $info);

        // 测试账号标记
        if (user_helper::is_test_dealers_user($store_info['user_id'])) {
            $info['is_enable']  = 0;
        }

        if($note) {
            $info['note'] = $note;
        }

        $return_score_data = _widget('score_record')->format_store_order_score($store_id, $order_goods_num, $order_price_sum);

        if($return_score_data) {
            $info['score'] = $return_score_data['score'];
        }

        // 二级经销商存在订单差价
        $info['diff_price']     = $diff_price;

        // 差价总额
        $info['diff_sum_price'] = $diff_sum_price;

        $order_id = _model('order')->create($info);

        if($order_id) {
            // 增加到订单的分支表中
            $user_info = user_helper::get_user_info($store_info['user_id']);

            //构架order_relation 关联表
            foreach ($order_goods_list as $k => $v) {
                $tmp_str = 'order_relation_info_'.$k;
                $tmp_param = $$tmp_str;
                $tmp_param['order_id'] = $order_id;
                _model('order_relation')->create($tmp_param);
            }

            order_helper::create_order_branch($order_id, $user_info);

            if($order_bulk_goods_num) {
                // 创建杯型数据
                foreach ($cup_num_data as $k => $v) {
                    $cup_num_data[$k]['order_id'] = $order_id;
                    $cup_num_data[$k]['store_id'] = $store_id;
                    $cup_num_data[$k]['cup_type'] = $k;
                    _model('order_cup')->create($cup_num_data[$k]);
                }
            }
            $order_id_encode = order_helper::order_id_encode($order_id);
            return array('提交订单成功', 'success', AnUrl('order/admin'));
        } else {
            return array('网络原因，提交订单失败', 'error', AnUrl('order/admin/trade/trade_order'));
        }
    }
    private function export_excel($table_data)
    {
        $title = array('序号', '商品信息', 'SKU信息', '单价', '数量');
        $file_name = date('Y-m-d') . '合伙人代理下单信息';
        $data = array(array(
            'name' => $file_name,
            'data' => array('title' => $title, 'data' => $table_data)
        ));
        return _widget('tools.excel')->export($file_name, $data);
    }
}
